package com.hsmpay.yl8583.service;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import com.hsmpay.base.PayBaseService;
import com.hsmpay.qian4.pojo.BalanceResult;
import com.hsmpay.qian4.pojo.PurchaseResult;
import com.hsmpay.qian4.pojo.RevocationResult;
import com.hsmpay.qian4.pojo.send.ICCardParam;
import com.hsmpay.qian4.pojo.send.SendParam;
import com.hsmpay.yl8583.utils.PackageUtil;
import com.hsmpay.utils.StringBUtils;
import com.hsmpay.utils.TimeUtils;
import com.hsmpay.utils.WriteFile;
import com.hsmpay.utils.YLCode;
import com.hsmpay.utils.system.ConConfig;

/**
 * E点支付
 * @author 颜铃璋
 */
public class IdeaioePayService extends PayBaseService{
	public static String debug = ConConfig.getAttribute("IDEAIOE_DAISHOU_DEBUG_STATUS");
	static Logger log = Logger.getLogger(IdeaioePayService.class);
	
	public IdeaioeSocketToBoss st = null;
	
	public String merchantId = "600000000000001";//商户号
	public String terminalId = "11111111";//终端号
	public String batch = "000001";//
	static WriteFile wf = new WriteFile("ds_Ideaioe");
	/**
	 * E点支付
	 * @param merchantId 商户号
	 * @param terminalId 终端号
	 * @param MPOSKey 母pos密钥
	 * @param batch 批次号
	 * @param MasterKey 主密钥（密文）
	 * @param PinKey 
	 * @param MacKey  单des  使用对称3des 
	 */
	public IdeaioePayService(String merchantId,String terminalId,String batch,String MasterKey,String PinKey,String MacKey,String trkKey){
		this.merchantId = merchantId;
		this.terminalId = terminalId;
		this.batch = batch;
		st = new IdeaioeSocketToBoss(merchantId,terminalId,batch,MasterKey,PinKey,MacKey,trkKey);
	}
	
	
	/**0_00_000001_79244599CC1AAC488B71D9EC011EEE58_A5C61E1B86229195E87EC8A890B052F6
	 * 0_00_000001
	 * 签到  
	 * @return 0_00_000001_79244599CC1AAC488B71D9EC011EEE58_A5C61E1B86229195E87EC8A890B052F6
	 * @throws Exception
	 */
	public String login(String bankOrderNum)throws Exception{//批次号 使用的是终端
		String result = "-1_ _ _ _ _ ";
		if(!isFormal()){
			log.debug("测试环境");
			result = "0_00_000001_79244599CC1AAC488B71D9EC011EEE58_956D675C0B414A71956D675C0B414A71_7CCECC48743EDB8F1C187A4F4AC8496A";
		}else{
			String ter = st.Login0800(bankOrderNum);//0_00_000001_96145D1E0E8F17F6497E9A211D401DA9_956D675C0B414A71FFFFFFFF39A05F15
			String[] terA = ter.split("_");
			log.debug("E点支付socket签到返回ter："+ter);
			
			if(!"-1".equals(terA[0])){
				if("00".equals(terA[1])){
					result = ter;
				}else{
					result = "0_"+terA[1]+" _ _ _ _ ";
				}
			}
		}
		log.debug("E点支付socket签到返回："+result);
		return result;
	}
	
	
	
	/**
	 * 查询余额
	 * @param send
	 * @throws Exception
	 * return reqCode reqMsg balance 单位是元
	 */
	public BalanceResult balanceEnquiry(SendParam send)throws Exception{
		BalanceResult br = new BalanceResult();
		br.setAccountNumber(send.getAccountNumber());//卡号
		br.setBalanceCurrency("RMB");//币种
		String resStr = "";
		if(!isFormal()){
			log.debug("测试环境");
			resStr = "0_00_储蓄帐户 ￥259959.17";
		}else{
			send.setTrack3Data("");//####屏蔽3磁道
			String bit14 = getIcc14(send.getIccParam());
			String bit23 = getIcc23(send.getIccParam());
			String bit55 = getIcc55(send.getIccParam());
			resStr = st.Query(send.getTrack2Data(), send.getTrack3Data(), send.getPin(),send.getAccountNumber(),send.getBankOrderNum(),bit23,bit55,bit14);
		}
		log.debug("E点支付socket查询余额响应："+resStr);
		String[] resArray = resStr.split("_");
		if("-1".equals(resArray[0])){
			br.setReqCode("9999");
			br.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
		}else{
			String reqCode =  StringBUtils.supplyAll(resArray[1], 4);
			br.setReqCode(reqCode);
			if("0000".equals(reqCode)){
				br.setReqMsg("查询余额成功！");
				String money = resArray[2].split("￥")[1];//单位是元
				Long balance = (long)(Double.parseDouble(money) * 100);//乘以100 变成分
				br.setBalance(balance.toString());
			}else{
				br.setReqMsg(null == YLCode.getMsg(resArray[1]) ? "查询余额失败！" : YLCode.getMsg(resArray[1]));
			}
		}
		return br;
	}
	
	/**
	 * 收款
	 * @param send
	 * @param pinKey
	 * @param macKey
	 * @return
	 * @throws Exception
	 */
	public PurchaseResult billPayment(SendParam send)throws Exception{
		PurchaseResult rs = new PurchaseResult();
		String money = StringBUtils.supplyAll(send.getTransAmt(), 12);
		String resStr = "";
		if(!isFormal()){
			log.debug("测试环境");
			resStr = "0_6226220112722482_000000000001_100011_150602_0807_ _000002350153_151878_00";
//			resStr = "0_6226220112722482_000000000001_100011_ _ _ _000005558216_ _55";
		}else{
			send.setTrack3Data("");//####屏蔽3磁道
			String bit14 = getIcc14(send.getIccParam());
			String bit23 = getIcc23(send.getIccParam());
			String bit55 = getIcc55(send.getIccParam());
			resStr = st.BillPayment(send.getTrack2Data(), send.getTrack3Data(), send.getPin(),money , send.getAccountNumber(),send.getBankOrderNum(),bit23,bit55,bit14);
		}
		log.debug("E点支付socket消费响应："+resStr);
		String[] resArray = resStr.split("_");
		if("-1".equals(resArray[0])){//
			rs.setStatus(0);//
			rs.setReqCode("9999");
			rs.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
		}else{
			rs.setStatus(1);//
			String reqCode =  StringBUtils.supplyAll(resArray[resArray.length-1], 4);
			rs.setReqCode(reqCode);
			rs.setAccountNumber(resArray[1]);
			rs.setBatchId(send.getBatchId());//批次号
			//rs.setAccountNumber(resArray[2]);//金额
			rs.setBankOrderNum(resArray[3]);//流水号
			rs.setBankTransTime(resArray[4]);//交易时间
			rs.setBankTransDate(resArray[5]);//交易日期
			rs.setExpireDate(resArray[6]);//有效期
			rs.setBankRef(resArray[7]);//参考号 37
			rs.setAuthorizationCode(resArray[8]);//授权号 38
			if("0000".equals(reqCode)){
				rs.setReqMsg("收款成功");
			}else{
				log.debug("------------"+resArray[1]+"------------");
				rs.setReqMsg( null == YLCode.getMsg(resArray[resArray.length-1]) ? "交易失败！" : "交易失败-"+YLCode.getMsg(resArray[resArray.length-1]));
			}
		}
		return rs;
	}
	
	/**
	 * 冲正接口
	 * @param send
	 * @param pinKey
	 * @param macKey
	 * @return
	 * @throws Exception
	 */
	public RevocationResult unBillPayment(SendParam send)throws Exception{
		RevocationResult rr = new RevocationResult();
		String money = StringBUtils.supplyAll(send.getTransAmt(), 12);
		String authorizationCode = send.getAuthorizationCode();
		String bankRef = send.getBankRef();
		if(null == authorizationCode) authorizationCode = "";
		if(null == bankRef) bankRef = "";
		
		String resStr = "";
		if(!isFormal()){
			log.debug("测试环境");
			resStr = "0_ _000000000001_100011_ _ _ _000002350153_151878_00_ _ ";
		}else{
			send.setTrack3Data("");//####屏蔽3磁道
			String bit14 = getIcc14(send.getIccParam());
			String bit23 = getIcc23(send.getIccParam());
			String bit55 = getIcc55(send.getIccParam());
			String track3Data = null == send.getTrack3Data() ? "" : send.getTrack3Data();
			
			String bit62 = batch+send.getOrgTransId()+TimeUtils.dateString(send.getOrgTransTime(), "MMdd");
			resStr = st.unBillPayment(send.getTrack2Data(), track3Data, money,send.getAccountNumber(),send.getBankOrderNum(),bankRef,authorizationCode,bit23,bit55,bit14,bit62)+" ";
		}
		log.debug("E点支付socket冲正接口响应："+resStr);
		String[] resArray = resStr.split("_");
		
		if("-1".equals(resArray[0])){//
			rr.setStatus(0);//
			rr.setReqCode("9999");
			rr.setReqMsg("由于网络原因，银联接口异常，请稍候再试！");
		}else{
			rr.setStatus(1);//
			String reqCode =  StringBUtils.supplyAll(resArray[resArray.length-3], 4);
			rr.setReqCode(reqCode);
			//resArray[1] 主帐号 resArray[2]  金额  resArray[3] 流水号  resArray[4] 交易时间  resArray[5] 交易日期  resArray[6] 失效日期  resArray[7] 参考号  resArray[8] 授权号  
			rr.setAccountNumber(resArray[1]);
			rr.setBankOrderNum(resArray[3]);
			rr.setBankTransTime(resArray[4]);
			rr.setBankTransDate(resArray[5]);
			rr.setExpireDate(resArray[6]);
			rr.setBankRef(resArray[7]);
			rr.setAuthorizationCode(resArray[8]);
			if("0000".equals(reqCode)){
				rr.setReqMsg("冲正成功");
			}else{
				rr.setReqMsg( null == YLCode.getMsg(resArray[resArray.length-3]) ? "冲正失败！" : "冲正失败-"+YLCode.getMsg(resArray[resArray.length-3]));
			}
		}
		return rr;
	}
	
	/**
	 * 55域
	 * @param iccParam
	 * @return
	 */
	private String getIcc55(ICCardParam iccParam){
		if(null == iccParam || StringUtils.isEmpty(iccParam.getIcCardYu())) return "";
		String bit55Str = iccParam.getBit55();
		log.debug("IC卡 bit55："+bit55Str);
		return bit55Str;
	}
	
	/**
	 * 有效期 返回4位  5F24的值前4个字符  有效期  5F24是：YYMMDD
	 * @param p_5f24
	 * @return
	 */
	private static String getIcc14(ICCardParam iccParam){
		if(null == iccParam || StringUtils.isEmpty(iccParam.getP_5f24())) return "";
		String r = iccParam.getP_5f24().substring(0, 4);
		return r;
	}
	
	/**
	 * IC卡序列 5F34的值,5F34的值不足3位前补0
	 * @param p_5f24
	 * @return
	 */
	private String getIcc23(ICCardParam iccParam){
		if(null == iccParam || StringUtils.isEmpty(iccParam.getP_5f34())) return "";
		String r = iccParam.getP_5f34();
		if(r.length() < 4)
			r = StringBUtils.supplyAll(r, 4);
		return r;
	}
	
	public static void main(String args[])throws Exception{
//		String resStr = "0_ _000000000001_100011_ _ _ _000002350153_151878_00_ _";
//		log.debug(resStr.split("_")[resStr.split("_").length-2]);
		//getIcc14("230930");
		
//		String s = "0_00_储蓄帐户 ￥0.0";
//		String money = s.split("_")[2].split("￥")[1];//单位是元
//		log.debug(money);
		
		String s = "344244343436343930313544463434453437373338414138434345413437303343344433423934323843423639443144334137324539423545374439424645423141414337413235433931444343333032394535343543353731393539303742443534454339393638413446364346443833453932373836333533324341383438363830433836443035303538333539";
		
		//		String s1 = s.substring(0, 204);
//		String p_9F35 = s.substring(216, 224);
//		String bit55 = s1+p_9F35;
		
		log.debug(PackageUtil.toStringHex(s));
	}
}